//
//  FoundHomeViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/17.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "FoundHomeViewController.h"
#import "SDCycleScrollView.h"
#import "ScrollPhotoModel.h"
#import "HeadCollectionCell.h"
#import "BookingTableViewCell.h"
#import "ChooseTypeViewController.h"
#import "ChooseTypeMod.h"
#import "myBookingCell.h"
#import "LookMoreCell.h"
#import "ActivitieDetailsViewController.h"
#import "NoDataCell.h"

#define SECTIONHEADERHEIGHT 50.f

@interface FoundHomeViewController () <UITableViewDataSource, UITableViewDelegate, SDCycleScrollViewDelegate, BookingCellDelegate>

@property (nonatomic, retain) SDCycleScrollView *cycleScrollView; // 第三方轮播图
@property (nonatomic, retain) UITableView *myTableV;
@property (nonatomic, retain) NSMutableArray *scrollPhotoArr; // 轮播图数组

@property (nonatomic, retain) NSMutableDictionary *myBookingDic; // 我的订阅内容大字典

@property (nonatomic, assign) NSInteger myBookingCont;
@property (nonatomic, retain) NSMutableArray *myKeyArr; // 接收订阅数组
@property (nonatomic, retain) NSMutableArray *tempArr; // 暂时存请求数据

@end

@implementation FoundHomeViewController
- (void)dealloc
{
    [_cycleScrollView release];
    [_myTableV release];
    [_scrollPhotoArr release];
    [_myBookingDic release];
    [_myKeyArr release];
    [_tempArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.myBookingCont = 0;
    self.scrollPhotoArr = [NSMutableArray array];
    self.myBookingDic = [NSMutableDictionary dictionary];
    self.tempArr = [NSMutableArray array];
//    self.myBookingSortArr = [NSMutableArray array];
    
    
    self.myTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -  49 - 64) style:UITableViewStylePlain];
    self.myTableV.backgroundColor = [UIColor clearColor];
    self.myTableV.dataSource = self;
    self.myTableV.delegate = self;
    self.myTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableV registerClass:[myBookingCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableV registerClass:[HeadCollectionCell class] forCellReuseIdentifier:@"headCell"];
    [self.myTableV registerClass:[BookingTableViewCell class] forCellReuseIdentifier:@"bookingCell"];
    [self.myTableV registerClass:[LookMoreCell class] forCellReuseIdentifier:@"moreCell"];
    [self.view addSubview:self.myTableV];
    [_myTableV release];

    [self addHeaderRefresh];
    
    // 接收城市改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homeRefurbish:) name:@"homeRefurbish" object:nil];
    
    
    // 接收订阅改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BookingRefurbish:) name:@"BookingRefurbish" object:nil];
    
}
#pragma mark - 城市改变通知
- (void)homeRefurbish:(NSNotification *)sender
{
//    NSString *cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"];
//    NSLog(@"++++++++%@ %@", cityName, [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"])
    // 马上进入刷新状态
    [self.myTableV.header beginRefreshing];
    
    
}
#pragma mark - 订阅改变通知
- (void)BookingRefurbish:(NSNotification *)sender
{
    self.myKeyArr = [sender object];
    self.myBookingCont = 0;
    
    [[Singleton shareSingleton] exeWithSQL:@"DELETE FROM chooseType"];
    
    for (ChooseTypeMod *mod in self.myKeyArr) {
        
        [[Singleton shareSingleton] exeWithSQL:[NSString stringWithFormat:@"INSERT INTO chooseType(Id, isTrue, name) VALUES('%@', '%@', '%@')", mod.Id, mod.isTrue, mod.name]];
        [self getContentWithMod:mod];
    }
      
}
#pragma mark - 下拉刷新
-(void)addHeaderRefresh
{
    self.myTableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        NSLog(@"下拉刷新");
        [self getUpdate];
        
        self.myKeyArr = [[Singleton shareSingleton] selectChooseTypeWithSQL:@"SELECT * FROM chooseType"];
        
        for (ChooseTypeMod *mod in self.myKeyArr) {
            [self getContentWithMod:mod];
        }
        
    }];
    // 马上进入刷新状态
    [self.myTableV.header beginRefreshing];
}
#pragma mark - 轮播图
- (SDCycleScrollView *)cycleScrollView
{
    if (nil == _cycleScrollView) {
        //网络加载 --- 创建带标题的图片轮播器
        self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 180) imageURLStringsGroup:nil];
        self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        self.cycleScrollView.delegate = self;
        self.cycleScrollView.dotColor = [UIColor colorWithRed:0.45 green:0.32 blue:0.35 alpha:1]; // 自定义分页控件小圆标颜色
        self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeholder"];
        //         --- 轮播时间间隔，默认1.0秒，可自定义
        self.cycleScrollView.autoScrollTimeInterval = 4.0;
    }
    return _cycleScrollView;
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SECTIONHEADERHEIGHT)];
    view.backgroundColor = [UIColor clearColor];
    
    if (section >= 2) {
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20 * AUTOSCREEN_WIDTH, 0, SCREEN_WIDTH - 30 * AUTOSCREEN_WIDTH, SECTIONHEADERHEIGHT)];
        nameLabel.font = [UIFont systemFontOfSize:16.f * AUTOSCREEN_WIDTH];
        nameLabel.textColor = [UIColor colorWithRed:0.51 green:0.47 blue:0.48 alpha:1];
        
        // 防止crash
        if (self.myBookingDic.allKeys.count <= 0) {
           nameLabel.text = @"程序出错啦~";
        } else {
            NSString *key = [self.myBookingDic.allKeys objectAtIndex:section - 2];
            nameLabel.text = key;
        }
        [view addSubview:nameLabel];
        [nameLabel release];
    }
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 0.f;
    } else if (1 == section) {
        return 8.f;
    }
    return SECTIONHEADERHEIGHT;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return 110.f * AUTOSCREEN_HEIGHT;
    } else if (1 == indexPath.section) {
        return 50.f * AUTOSCREEN_HEIGHT;
    } else if (indexPath.row > 2) {
        return 45.f * AUTOSCREEN_HEIGHT;
    }
    
    
    return (SCREEN_HEIGHT - 50 - 49 - 64) / 3.f;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 2 + self.myBookingDic.allKeys.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 == section || 1 == section) {
        return (NSInteger)1;
    }
    
    
    NSMutableArray *arr = [self.myBookingDic objectForKey:[self.myBookingDic.allKeys objectAtIndex:section - 2]];
    if (arr.count > 3) {
        return 4;
    }
    
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    static NSString *headStr = @"headCell";
    static NSString *bookingStr = @"bookingCell";
    static NSString *moreStr = @"moreCell";

    
    if (0 == indexPath.section) {
        
        HeadCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:headStr];

//        cell.backgroundColor = [UIColor clearColor];
        
        [self addColorChangedBlock:^{
            
            cell.contentView.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
            cell.contentView.normalBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        }];

        return cell;
    } else if (1 == indexPath.section) {
        BookingTableViewCell *bookingCell = [tableView dequeueReusableCellWithIdentifier:bookingStr];
        
        bookingCell.delegate = self;
        bookingCell.backgroundColor = [UIColor whiteColor];
        // cell 不能点击
        [bookingCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        
        [self addColorChangedBlock:^{
            
            bookingCell.contentView.nightBackgroundColor = [ColorSingleton shareSingleton].cellColor;
            bookingCell.contentView.normalBackgroundColor = [ColorSingleton shareSingleton].cellColor;
        }];
        
        return bookingCell;
    }
    
    if (indexPath.row > 2) {
        LookMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:moreStr];
        cell.backgroundColor = [UIColor clearColor];
        


        return cell;

    }
    
    
    
    // 防止crash
    if (self.myBookingDic.allKeys.count < indexPath.section - 2) {
        static NSString *cellStr = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        if (nil == cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellStr] autorelease];
        }
        cell.textLabel.text = @"程序出错啦~";
        return  cell;
    }
    
    myBookingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    
    NSString *key = [self.myBookingDic.allKeys objectAtIndex:indexPath.section - 2];
    NSMutableArray *arr = [self.myBookingDic objectForKey:key];
    ContentMod *mod = [arr objectAtIndex:indexPath.row];
    
    cell.contentMod = mod;
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 选中时有置灰效果, 离开时消失选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 防止crash
    if (self.myBookingDic.allKeys.count < indexPath.section - 2) {
        NSLog(@"程序出错!");
    }
    
    
    NSString *key = [self.myBookingDic.allKeys objectAtIndex:indexPath.section - 2];
    NSMutableArray *arr = [self.myBookingDic objectForKey:key];
    ContentMod *mod = [arr objectAtIndex:indexPath.row];
    
    if (indexPath.row > 2) {
        
        
        
        NSLog(@"jkjlajlgjdlgjdlkgjd");
        
    } else {
        
        ActivitieDetailsViewController *activitieVC = [[ActivitieDetailsViewController alloc] init];
        activitieVC.activityId = mod.activityId;
        activitieVC.activityTitle = mod.title;
        // 隐藏
        activitieVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:activitieVC animated:YES];
        [activitieVC release];
        
        [self.delegate navigationViewWithIsHidden:YES];
    }

}
#pragma mark - 跳转到分类选择页面
- (void)goToChooseType
{
    ChooseTypeViewController *chooseVC = [ChooseTypeViewController shareChooseTypeViewController];
    
    [self presentViewController:chooseVC animated:YES completion:^{
  
    }];
}
- (void)getUpdate
{
    
    // 让菊花旋转起来
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    hub.labelText = @"努力加载中...";
    
    
    NSString *cityid = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"];
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/getjingxuandatav2.json?cityid=%@&source=10344&version=20001", cityid];
    
    [AppTools getAFNet:url block:^(id result) {
        [self.scrollPhotoArr removeAllObjects];
        
        
        NSMutableDictionary *bigDic = result;
        NSMutableArray *bigDataArr = [bigDic objectForKey:@"data"];
        
        // 如果没有数据不再解析数据
        if (bigDataArr.count == 0) {
            //结束下拉上拉刷新
            [self.myTableV.header endRefreshing];
            [self.myTableV.footer endRefreshing];
            [hub hide:YES];

            return;
        }
        
        for (NSMutableDictionary *dic in bigDataArr) {
            // 获取轮播图数据
            if ([[dic objectForKey:@"typex"] isEqualToString:@"model8"]) {
                NSMutableArray *topimgArr = [[dic objectForKey:@"datax"] objectForKey:@"topimg"];
                for (NSMutableDictionary *topimgDic in topimgArr) {
                    ScrollPhotoModel *topMod = [ScrollPhotoModel modelWithDictionary:topimgDic];
                    [self.scrollPhotoArr addObject:topMod];
                }
            }
        }
        
        // 数据解析完毕
        // 创建轮播图数组
        NSMutableArray *scrollDataArray = [NSMutableArray array];
        for (ScrollPhotoModel *topMod in self.scrollPhotoArr) {
            [scrollDataArray addObject:topMod.pic];
        }
        //结束下拉上拉刷新
        [self.myTableV.header endRefreshing];
        [self.myTableV.footer endRefreshing];
        [hub hide:YES];

        // 有轮播图是添加, 没有就设置为nil
        if (scrollDataArray.count > 0) {
            
            self.myTableV.tableHeaderView = self.cycleScrollView;
            self.cycleScrollView.imageURLStringsGroup = scrollDataArray;
            
        } else {
            // 去除头视图
            self.myTableV.tableHeaderView = nil;
            [self.myTableV reloadData];
        }
        
        
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
        }];
        
        //结束下拉上拉刷新
        [self.myTableV.header endRefreshing];
        [self.myTableV.footer endRefreshing];
        [hub hide:YES];
    }];
}
#pragma mark - 获取内容数据
- (void)getContentWithMod:(ChooseTypeMod *)mod
{
    NSString *cityid = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityid"];
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/projlistnew.json?cateid=%@&cityId=%@&etime=&order=pri&pindex=0&psize=4&source=10344&stime=&version=20001", mod.Id, cityid];
    
    [AppTools getAFNet:url block:^(id result) {
        if (0 == self.myBookingCont) {
            [self.myBookingDic removeAllObjects];
        }
        self.myBookingCont++;
       
        NSMutableDictionary *bigDic = result;
        
        NSMutableArray *tempArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in [bigDic objectForKey:@"data"]) {
            ContentMod *contentMod = [ContentMod modelWithDictionary:dic];
            [tempArr addObject:contentMod];
        }
        [self.myBookingDic setObject:tempArr forKey:mod.name];

        
         if (self.myBookingCont >= self.myKeyArr.count) {
    
             
             NSMutableArray *deleteArr = [NSMutableArray array];
             // 找到没有数据的分组key存到deleteArr里
             for (NSString *key in self.myBookingDic) {

                 NSMutableArray *arr = [self.myBookingDic objectForKey:key];
                 if (0 == arr.count) {
                     [deleteArr addObject:key];
                 }
             }
             // 遍历deleteArr删除保存的key
             for (NSString *key in deleteArr) {
                 [self.myBookingDic removeObjectForKey:key];
             }
             
             // 刷新tableview
             [self.myTableV reloadData];
        }
        

        
    } errorBlock:^(NSError *error) {
        
        [self NetworkError:^{
        }];
        
        //结束下拉上拉刷新
        [self.myTableV.header endRefreshing];
        [self.myTableV.footer endRefreshing];
    
    }];
}
#pragma mark - 去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = SECTIONHEADERHEIGHT;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end